/*eslint-disable*/
import {login, logout, editLoginUserInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/auth'
import router, {resetRouter} from '@/router'
import Layout from '@/layout'
import md5 from 'js-md5'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  menus: [],
  permissionList: [],
  authorityList: [],
  userInfo: {}
}

const menuList =
  [
    {
      'menuId': 1,
      'menuType': '1',
      'menuName': '系统管理',
      'menuPath': 'system',
      'menuComponent': '/layout',
      'parentId': null,
      'sortNum': 1,
      'children': [
        {
          'menuId': 101,
          'menuType': '3',
          'menuName': '用户管理',
          'menuPath': '/system/userlist',
          'menuComponent': '/system/user/user-list',
          'parentId': 1,
          'sortNum': 1,
          'children': null
        },
        {
          'menuId': 102,
          'menuType': '3',
          'menuName': '角色管理',
          'menuPath': '/system/rolelist',
          'menuComponent': '/system/role/role-list',
          'parentId': 1,
          'sortNum': 2,
          'children': null
        },
        {
          'menuId': 103,
          'menuType': '3',
          'menuName': '菜单管理',
          'menuPath': '/system/menu/menulist',
          'menuComponent': '/system/menu/menu-list',
          'parentId': 1,
          'sortNum': 3,
          'children': null
        },
        {
          'menuId': 104,
          'menuType': '3',
          'menuName': '系统代码',
          'menuPath': '/system/data/datalist',
          'menuComponent': '/system/data/data-list',
          'parentId': 1,
          'sortNum': 4,
          'children': null
        }
      ],
    },
    {
      'menuId': 2,
      'menuType': '1',
      'menuName': '开发工具',
      'menuPath': 'devTool',
      'menuComponent': '/layout',
      'parentId': null,
      'sortNum': 2,
      'children': [
        {
          'menuId': 201,
          'menuType': '3',
          'menuName': '构建代码',
          'menuPath': '/devTool/createCode',
          'menuComponent': '/devTool/createCode/code-list',
          'parentId': 2,
          'sortNum': 1,
          'children': null
        }
      ],
    },
    {
      'menuId': 3,
      'menuType': '1',
      'menuName': '业务主数据',
      'menuPath': 'businessData',
      'menuComponent': '/layout',
      'parentId': null,
      'sortNum': 3,
      'children':
        [
          {
            'menuId': 31,
            'menuType': '2',
            'menuName': '工厂布局',
            'menuPath': 'factorylayout',
            'menuComponent': '',
            'parentId': 3,
            'sortNum': 1,
            'children':
              [
                {
                  'menuId': 311,
                  'menuType': '3',
                  'menuName': '工厂',
                  'menuPath': '/businessData/factorylayout/factory',
                  'menuComponent': '/businessData/factorylayout/factory-list',
                  'children': null,
                  'parentId': 31,
                  'sortNum': 1
                }
              ]
          },
        ],
    },
  ]

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_PERMISSION: (state, permissionList) => {
    state.permissionList = permissionList
  },
  SET_AUTHORIZE: (state, authorityList) => {
    state.authorityList = authorityList
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENU: (state, menus) => {
    state.menus = menus
  },
  CACHE_LOGIN_INFO: (state, data) => {
    sessionStorage.setItem('loginInfo', JSON.stringify(data))
    // const menus = genMenus(menuList)//静态菜单
    const menus = genMenus(data.menuList)//动态加载菜单
    router.addRoutes(menus)
    state.name = data.username//用户登录名
    state.permissionList = data.permissionList//用户按钮权限
    state.authorityList = data.authorityList//用户业务权限
    state.menus = menus
    // state.userInfo = data
    setToken(data.token)
  },
  CLEAR_LOGIN_INFO: (state, data) => {

  }
}

//菜单图标配置
const ICONS = {
  '系统管理': 'el-icon-setting',
  '业务主数据': 'el-icon-cpu',
  '文件管理': 'el-icon-folder',
  '任务管理': 'el-icon-cpu',
  '开发工具': 'el-icon-s-tools',
  '打印测试': 'el-icon-printer',
  '运维监控': 'el-icon-video-camera-solid',
  '质量管理': 'el-icon-s-check',
  '计划管理': 'el-icon-goods',
  '生产控制': 'el-icon-truck',
}

const genMenus = (menuList) =>{
  //菜单列表
  const menus = []
  if (menuList) {
    for (const pMenu of menuList) {
      const title = pMenu.menuName
      const path = pMenu.menuPath
      //后台返回的菜单列表
      const childrenJava = pMenu.children
      if (!childrenJava || childrenJava.every(item => hiddenMenus.includes(item.menuName))) {
        continue
      }
      //单个菜单对象
      const menu = {
        component: Layout,
        redirect: 'noRedirect',
        alwaysShow: true,
        meta: {
          title,
          icon: ICONS[title] || '',
        }
      }
      if (path) {
        menu.path = path
        menu.name = path.slice(0, 1).toUpperCase() + path.slice(1)
        //如果该主目录存在子菜单
        if (childrenJava) {
          //过滤掉需要隐藏的菜单
          pMenu.children = childrenJava.filter(item => !hiddenMenus.includes(item.menuName))
          //构建当前菜单对象的子菜单
          genChildMenus(menu, childrenJava)
        }
        menus.push(menu)
      }
    }
  }
  return menus
}

/**
 * 生成子菜单
 * @param menu 前端单个菜单对象
 * @param childrenJava 后台返回的菜单列表
 */
const genChildMenus = (menu, childrenJava) => {
  const childrenList = []
  for (const childMenu of childrenJava) {
    const {menuName: title, menuPath, menuComponent, children, menuType} = childMenu //后台返回的菜单对象
    if (children && children.length>0) {
      //存在子菜单
      if(menuType=='2'){
        menu.children = childrenList
        const menuSecond = {
          path: menuPath || '/layout',
          component: {render: h => h("router-view")},
          name: menuPath.slice(0, 1).toUpperCase() + menuPath.slice(1),
          redirect: 'noRedirect',
          alwaysShow: true,
          meta: {
            title,
            icon: ICONS[title] || '',
          }
        }
        childrenList.push(menuSecond)
        for (const childMenu of children) {
          genChildMenus(menuSecond, children)
        }
      }
    } else {
      if (menuComponent && menuPath) {
        let name = menuComponent.substring(menuComponent.lastIndexOf('/') + 1)
        name = name.slice(0, 1).toUpperCase() + name.slice(1)
        childrenList.push(
          {
            path: menuPath || '/layout',
            component: resolve => require([`@/views${menuComponent}`], resolve), // () => import(`@/views${component}`),
            name: name.replace(/-(\w)/g, ($0, $1) => $1.toUpperCase()),
            hidden: hiddenMenus.includes(title),
            meta: {
              title,
              noCache: nocacheMenus.includes(title),
            }
          })
      }
    }
    menu.children = childrenList
  }

}

//需要隐藏的菜单列表
const hiddenMenus = []
//不缓存的菜单列表
const nocacheMenus = []

const actions = {
  // user login
  login({commit}, param) {
    return new Promise((resolve, reject) => {
      param.password = md5(param.password)
      login(param).then(ret => {
        commit('CACHE_LOGIN_INFO', ret)
        commit('SET_TOKEN', ret.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  relogin({commit}) {
    commit('SET_TOKEN', '')
    removeToken()
    resetRouter()
  },
  editLoginUserInfo({commit, state}, param) {
    return new Promise((resolve, reject) => {
      editLoginUserInfo(param).then(ret => {
        state.name = param.name
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
